import json
import re


def fstring(item):
    if item is None:
        return ""
    if isinstance(item, list):
        if len(item) == 1:
            return str(item[0]).strip()
        else:
            return "".join([i.strip() for i in item])
    else:
        return str(item).strip()


def frange(item):
    if item is None:
        return ""
    if isinstance(item, list):
        if len(item) == 0:
            return ""
        elif len(item) == 1:
            return str(item[0]).strip()
        elif len(item) > 1:
            return "%s - %s" % (str(item[0]).strip(), str(item[1]).strip())
        else:
            return str(item)
    else:
        return str(item).strip()


def fnewlines(item):
    r = "".join(item)
    r = re.sub(r'\n +', '', r)
    r = re.sub(r'\n+', '\n', r)
    return r.strip()


def fjson(item):
    try:
        if item is None or (isinstance(item, list) and len(item) <= 0):
            return ""
        if isinstance(item, list) and len(item) > 0 or isinstance(item, str):
            return json.loads(fstring(item).replace("\\\"", "\""))
        else:
            return str(item).strip()
    except:
        return str(item).strip()


def fjsonarray(item, key=None):
    try:
        fields = [json.loads(obj)[key] for obj in item]
        return fields
    except:
        return str(item).strip()


def fregex(pattern, text, index=0):
    matcher = re.search(pattern, text, flags=re.IGNORECASE)
    if matcher:
        return matcher.group(index)
    else:
        return ''


def delta_days(time1, time2):
    if time1 is None or time2 is None:
        return None
    delta = (time2.tm_year - time1.tm_year) * 365
    delta += time2.tm_yday - time1.tm_yday
    return abs(delta)